﻿using BaseDal;
using Models;
using System;
using System.Collections.Generic;
using System.Data;

namespace BaseBll
{
    public class PurchaseOrderBll
    {
        private static readonly Lazy<PurchaseOrderBll> _instance = new Lazy<PurchaseOrderBll>(() => new PurchaseOrderBll());

        public static PurchaseOrderBll Instance { get; } = _instance.Value;

        private PurchaseOrderBll()
        { }

        /// <summary>
        /// 查询数据是否存在
        /// </summary>
        /// <param name="strWhere"></param>
        /// <returns></returns>
        public bool IsExist(string strWhere)
        {
            return PurchaseOrderDal.Instance.IsExist(strWhere);
        }

        /// <summary>
        /// 查询分页数据
        /// </summary>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <param name="strWhere"></param>
        /// <param name="filedOrder"></param>
        /// <param name="recordCount"></param>
        /// <returns></returns>
        public DataTable GetPageList(int pageSize, int pageIndex, string strWhere, string filedOrder, out int recordCount)
        {
            return PurchaseOrderDal.Instance.GetPageList(pageSize, pageIndex, strWhere, filedOrder, out recordCount);
        }

        /// <summary>
        /// 查询数据
        /// </summary>
        /// <param name="strWhere"></param>
        /// <returns></returns>
        public List<PurchaseOrderHead> GetList(string strWhere)
        {
            return PurchaseOrderDal.Instance.GetList(strWhere);
        }

        /// <summary>
        /// 根据id查询实体类
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public PurchaseOrderHead GetModelById(decimal id)
        {
            return PurchaseOrderDal.Instance.GetModelById(id);
        }

        /// <summary>
        /// 根据主表ID查询所有物品
        /// </summary>
        /// <param name="headID"></param>
        /// <returns></returns>
        public List<PurchaseOrderBody> GetItemList(int headID)
        {
            return PurchaseOrderDal.Instance.GetItemList(headID);
        }

        /// <summary>
        /// 增加一条数据
        /// </summary>
        public bool AddPurchaseOrder(PurchaseOrderHead model)
        {
            return PurchaseOrderDal.Instance.AddPurchaseOrder(model);
        }

        /// <summary>
        /// 更新一条数据
        /// </summary>
        public bool UpdatePurchaseOrder(PurchaseOrderHead model)
        {
            return PurchaseOrderDal.Instance.UpdatePurchaseOrder(model);
        }

        /// <summary>
        /// 删除一条数据，及子表所有相关数据
        /// </summary>
        public bool DeletePurchaseOrder(int ID)
        {
            return PurchaseOrderDal.Instance.DeletePurchaseOrder(ID);
        }

        /// <summary>
        /// 修改状态（0：审批中；1：已审批；2：暂存）
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public int UpdateStatus(int id, int status)
        {
            return PurchaseOrderDal.Instance.UpdateStatus(id, status);
        }

        /// <summary>
        /// 验证model各字段合法性
        /// </summary>
        /// <param name="model"></param>
        /// <param name="msg">错误信息</param>
        /// <returns></returns>
        public bool VerifyModel(PurchaseOrderHead model, ref string msg)
        {
            string strWhere;
            if (model.ID > 0)
            {
                strWhere = " and PO_OrderNo='" + model.PO_OrderNo + "' and ID !=" + model.ID;
            }
            else
            {
                strWhere = " and PO_OrderNo='" + model.PO_OrderNo + "'";
            }
            if (IsExist(strWhere))
            {
                msg = "订单编号已存在";
                return false;
            }

            // 如果关联申请单，则验证数量，不能超过申请的数量  TODO

            // 获取公司名称
            Department company = DeptBll.Instance.GetModelById(model.PO_CompanyId);
            if (company != null)
            {
                model.PO_CompanyName = company.FullName;
            }
            else
            {
                msg = "所选公司不存在";
                return false;
            }

            // 获取部门名称
            Department dept = DeptBll.Instance.GetModelById(model.PO_DeptId);
            if (dept != null)
            {
                model.PO_DeptName = dept.FullName;
            }
            else
            {
                msg = "所选部门不存在";
                return false;
            }

            // 获取供应商名称
            Supplier supplier = SupplierBll.Instance.GetModelById(model.PO_SupplierId);
            if (supplier != null)
            {
                model.PO_SupplierName = supplier.S_Name;
            }
            else
            {
                msg = "所选供应商不存在";
                return false;
            }

            return true;
        }

        /// <summary>
        /// 通过申请单ID 物品编号获取物品
        /// </summary>
        /// <param name="headID"></param>
        /// <param name="itemID"></param>
        /// <returns></returns>
        public PurchaseOrderBody GetItemByHeadIDAndItemID(decimal headID, string itemID)
        {
            return PurchaseOrderDal.Instance.GetItemByHeadIDAndItemID(headID, itemID);
        }

        // 定义一个私有的对象作为锁
        private readonly object _lockObject = new object();

        /// <summary>
        /// 采购变更单审核通过时，修改采购单的"PO_BuyQty（购买数量）PO_Texrate（税率）PO_TotalCost（总金额）" 字段
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool UpdOrderWithAudit(PurchaseAlterHead model)
        {
            lock (_lockObject)
            {
                List<PurchaseAlterBody> bodyList = model.ItemList;

                PurchaseOrderBody orderBody;
                PurchaseOrderBody orderBody1;
                List<PurchaseOrderBody> orderBodyList = new List<PurchaseOrderBody>();
                List<PurchaseOrderBody> orderBodyList1 = new List<PurchaseOrderBody>();
                foreach (PurchaseAlterBody alterBody in bodyList)
                {
                    if (alterBody.PA_BuyQty_Alter > 0 || alterBody.PA_TotalCost_Alter > 0)
                    {
                        orderBody = new PurchaseOrderBody();
                        orderBody = Instance.GetItemByHeadIDAndItemID(model.PA_OrderID, orderBody.PO_ItemID);

                        if (orderBody != null)
                        {
                            orderBody.PO_BuyQty = alterBody.PA_BuyQty_Alter;
                            //orderBody.PO_Texrate = alterBody.PA_Texrate_Alter == 0 ? orderBody.PO_Texrate : alterBody.PA_Texrate_Alter;
                            orderBody.PO_TotalCost = alterBody.PA_TotalCost_Alter;

                            orderBodyList.Add(orderBody);

                            orderBody1 = new PurchaseOrderBody();
                            orderBody1.PO_ApplyNo = orderBody.PO_ApplyNo;
                            orderBody1.PO_ItemID = orderBody.PO_ItemID;
                            orderBody1.PO_BuyQty = -alterBody.PA_BuyQty + alterBody.PA_BuyQty_Alter;
                            orderBodyList1.Add(orderBody1);
                        }
                    }
                }

                // 修改采购订单中的采购数量，与价格
                bool res = PurchaseOrderDal.Instance.UpdOrderQtytWithAudit(orderBodyList);
                if (res)
                {
                    // 修改采购申请中的采购数量
                    res = PurchaseRequestBll.Instance.UpdRequestWithAudit(orderBodyList1);
                }
                return res;
            }
        }
    }
}